import time

import serial
import  dp645

class TCo645:
    def __init__(self):
        self.config ={
            "comPort" :"COM13",
            "baudrate": 1200
        }
        self.devs ={}
        self.dps ={}
        self.dpList = []
        self.ser = None
        self.dpIndex =0
    def init(self):
        try:
            dps = dp645.dps
            for dp in dps:
                dev = None
                devCode = dp['devCode']
                if devCode in self.devs.keys():
                    dev = self.devs[devCode]
                else:
                    dev = {
                        "devCode":devCode,
                        "devCate": dp['devCate'],
                        "dps":{}
                    }
                    self.devs[devCode] = dev
                dp['dev'] = dev
                dp['ov'] = 0
                dp['nv'] = 0
                dp['tm'] = 0
                dpCode = dp['dpCode']
                dev['dps'][dpCode] = dp
                self.dps[dpCode] = dp
                self.dpList.append(dp)
        except Exception as er:
            print(er)

    def getDpCmdBytes(self , dp):
        res =[]
        try:
            addrBytes = bytes(reversed( bytes.fromhex(dp['devCode'])))
            res.append(0x68)
            for i in range(len(addrBytes)):
                res.append(addrBytes[i])
            res.append(0x68)
            res.append(0x11)
            res.append(0x4)
            res.append(0x33+dp['a3'])
            res.append(0x33+dp['a2'])
            res.append(0x33+dp['a1'])
            res.append(0x33+dp['a0'])
            cs = 0
            for i in range(len(res)):
                cs = cs + res[i]
                cs = cs % 256
            res.append(cs)
            res.append(0x16)

            txt = ' '.join([ hex(x) for x in res])
            #print('send',txt)
        except Exception as er:
            print(er)
        return  bytearray(res)

    def getValue(self , respBytes):
        res = 0
        try:
            pass
        except Exception as er:
            print(er)
        return 0

    def start(self):
        try:
            self.init()
            while 1>0 :
                self.readDp(100)

        except Exception as er:
            print(er)
    def stop(self):
        try:
            if self.ser!=None:
                self.ser.close()
            self.ser = None
        except Exception as er:
            print(er)
    def readDp(self, num):
        try:
            self.stop()
            comPort = self.config['comPort']
            baudrate = self.config['baudrate']

            ser = serial.Serial(comPort, baudrate , parity=serial.PARITY_EVEN, timeout=2)
            self.ser = ser


            dps = self.dpList
            for i in range(num):
                # if self.dpIndex>=118:
                #     print('dddddddddddddd',dp)
                if self.dpIndex % 10 ==0 :
                    print(len(self.dpList), self.dpIndex , time.time())
                dp = dps[self.dpIndex]
                try:
                    cmdBytes = self.getDpCmdBytes(dp)
                    sendLen = ser.write(cmdBytes)
                    ser.flush()
                    time.sleep(0.03)
                    rb = 0
                    recList = []
                    size = 0
                    flag = False
                    pos68= -1
                    p68th2 = False
                    while not flag:
                        recArray = ser.read(1)
                        if len(recArray)==1 :
                            rb = recArray[0]
                            recList.append(rb)
                            if len(recList)>7 and recList[-1]==0x68 :
                                if recList[-8]==0x68 and not p68th2:
                                    p68th2 = True
                                    pos68 = len(recList)  - 1
                            if rb == 0x16 and pos68> 8:
                                posSize =  pos68 + 2
                                size = recList[posSize]
                                recLen = posSize + size + 2 + 1
                                if recLen == len(recList):
                                    flag = True
                                if not flag:
                                    print('------------  error -----------------')
                        else:
                            time.sleep(0.1)
                            continue
                    txt = ' '.join([ hex(x) for x in recList])
                    #print('recv',txt)
                    dataBytes = bytearray( recList[17:17+size-4])
                    dataValue = int.from_bytes(dataBytes , byteorder='big')
                    dp['ov'] = dp['nv']
                    dp['nv'] = dataValue
                    dp['tm'] = time.time()
                except Exception as e1:
                    if not ser.is_open:
                        break
                    print(e1)
                self.dpIndex = self.dpIndex + 1
                if self.dpIndex  >= len( dps):
                    self.dpIndex =0
        except Exception as er:
            print(er)

co = TCo645()
co.start()
print(co.devs)